import { Context } from 'koa';
import { AuthService } from '../../services/system/authService';
import { createError } from '../../middleware/errorHandler';
import { RegisterDto, LoginDto } from '../../dtos/system/UserDto';
import { generateResponse,  } from '../../utils';

export class AuthController {
  private authService: AuthService;

  constructor() {
    this.authService = new AuthService();
  }

  // 用户注册
  register = async (ctx: Context): Promise<void> => {
    try {
      // 从验证中间件获取已验证的数据
      const registerData = ctx.state.validatedData as RegisterDto;

      const result = await this.authService.register(registerData);
      generateResponse(ctx, result)

    } catch (error: any) {
      if (error.status === 409) throw error; // 冲突错误直接抛出
      throw createError('注册失败', 400, error);
    }
  };

  // 用户登录
  login = async (ctx: Context): Promise<void> => {
    try {
      // 从验证中间件获取已验证的数据
      const loginData = ctx.state.validatedData as LoginDto;

      const result = await this.authService.login(loginData);
      generateResponse(ctx, result)

    } catch (error: any) {
      console.log(error,'wtf error')
      if (error.status === 401 || error.status === 403) throw error; // 认证错误直接抛出
      throw createError('登录失败', 400, error);
    }
  };

  // 获取当前用户信息
  getCurrentUser = async (ctx: Context): Promise<void> => {
    try {
      // 从中间件获取用户信息
      const user = ctx.state.user;

      if (!user) {
        throw createError('用户未认证', 401);
      }
      generateResponse(ctx, user)

    } catch (error: any) {
      throw createError('获取用户信息失败', 400, error);
    }
  };

  // 刷新 token
  refreshToken = async (ctx: Context): Promise<void> => {
    try {
      const user = ctx.state.user;

      if (!user) {
        throw createError('用户未认证', 401);
      }

      const token = await this.authService.refreshToken(user._id);
      generateResponse(ctx, token)

    } catch (error: any) {
      throw createError('刷新 token 失败', 400, error);
    }
  };
}

export default AuthController;